package com.gxa.learning.pc.controller;

import com.github.pagehelper.PageInfo;
import com.gxa.learning.core.common.ExceptionCode;
import com.gxa.learning.core.common.JsonResult;
import com.gxa.learning.core.exception.BusinessException;
import com.gxa.learning.core.pojo.Answer;
import com.gxa.learning.core.pojo.Question;
import com.gxa.learning.core.pojo.Score;
import com.gxa.learning.core.util.StringUtil;
import com.gxa.learning.pc.service.AnswerService;
import com.gxa.learning.pc.service.QuestionService;
import com.gxa.learning.pc.service.ScoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 操作题目的接口
 *
 * @Author ChenJ
 * @date 2021/12/02 16:11
 **/
@RestController
@RequestMapping("/question")
@Api(value = "QuestionController", tags = "操作题目的接口")
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @Autowired
    private AnswerService answerService;

    @Autowired
    private ScoreService scoreService;


    @GetMapping("/getList")
    @ApiOperation("获取全部题目的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "questionBankId", value = "questionBankId", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "status", paramType = "query"),
            @ApiImplicitParam(name = "uId", value = "uId", paramType = "query")
    })
    public Map<String, Object> getList(Long questionBankId, Long uId, Integer status) throws BusinessException {


        Map<String, Object> question = null;

        if (status == 0) {
            question = questionService.getQuestion(questionBankId);
        } else {
            question = questionService.getUserQuestion(uId, questionBankId);
        }

        if (question == null) {
            throw new BusinessException(ExceptionCode.WRONG_DATA);
        }

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("成功");
        jsonResult.setData(question);
        return jsonResult.getDataMap();
    }

    @PostMapping("/handRoll")
    @ApiOperation("交卷的接口")
    @ApiImplicitParam(name = "map", value = "map", paramType = "body")
    @Transactional
    public Map<String, Object> handRoll(@RequestBody Map<String, Object> question) throws BusinessException {

        System.out.println(question);

        // 先进行数据校验
        if (question == null) {
            throw new BusinessException(ExceptionCode.ARGUMENTS_NOT_NULL);
        }
        if (StringUtil.isEmpty(question.get("scoreId").toString())) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }
        if (StringUtil.isEmpty(question.get("passScore").toString())) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }
        if (StringUtil.isEmpty(question.get("scoreKey").toString())) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }
        if (StringUtil.isEmpty(question.get("userId").toString())) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }

        Object question1 = question.get("question");
        List<Map<String, Object>> list = (List) question1;
        Integer scoreNum = 0;
        for (Map<String, Object> map : list) {
            if (StringUtil.isEmpty(map.get("answer").toString()) ||
                    StringUtil.isEmpty(map.get("answerFill").toString()) ||
                    StringUtil.isEmpty(map.get("core").toString()) ||
                    StringUtil.isEmpty(map.get("questionId").toString())) {
                throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
            }
            if (map.get("answer").equals(map.get("answerFill"))) {
                scoreNum += Integer.valueOf(map.get("core").toString());
                System.out.println(scoreNum);
            }
            Answer answer = new Answer();
            // 添加学员题目的填写答案
            answer.setAnswerFill(map.get("answerFill").toString());
            // 学员编号
            answer.setUId(Long.valueOf(question.get("userId").toString()));
            // 题目编号
            answer.setQId(Long.valueOf(map.get("questionId").toString()));
            // 用户uuid生成考试编号
            answer.setScoreKey(question.get("scoreKey").toString());
            answerService.insert(answer);
        }

        Score score = scoreService.selectById(Long.valueOf(question.get("scoreId").toString()));
        // 交卷时设置状态为已考试
        score.setStatus(3);
        System.out.println("最终的分数");
        score.setScoreNum(scoreNum);
        // 如果学员考试的成绩大于通过考试则设置状态为通过
        if (Integer.valueOf(question.get("passScore").toString()) >= scoreNum) {
            score.setScoreResult(true);
        } else {
            // 否则设置为不通过
            score.setScoreResult(false);
        }
        // 提交试卷后修改学员关联的成绩表
        scoreService.updateById(score);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("成功");
        return jsonResult.getDataMap();
    }

    @PostMapping("/insert")
    @ApiOperation("添加题目的接口")
    @ApiImplicitParam(name = "question", value = "question", paramType = "body", dataTypeClass = Question.class)
    public Map<String, Object> insert(@RequestBody Question question) throws BusinessException {

        // 数据校验
        if (question.getQuestionBankId() == null) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }

        // 题目的添加操作
        Question insert = questionService.insert(question);

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("成功");
        return jsonResult.getDataMap();
    }

    @PostMapping("/getQList")
    @ApiOperation("获取题目列表的接口（包含模糊查询）")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "page", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "size", value = "size", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "questionBankId", value = "questionBankId", paramType = "query", dataType = "Long")
    })
    public Map<String, Object> getQList(@RequestParam Integer page, @RequestParam Integer size, @RequestParam Long questionBankId) throws BusinessException, IllegalAccessException {

        // 数据校验
        if (questionBankId == null) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }
        if (page == null) {
            page = 1;
        }
        if (size == null) {
            size = 10;
        }

        Question question = new Question();
        // 设置查询规则
        question.setQuestionBankId(questionBankId);
        PageInfo<Question> questionPageInfo = questionService.selectByPage(page, size, question);
        List<Question> list = questionPageInfo.getList();
        if (list.size() == 0) {
            throw new BusinessException(ExceptionCode.NO_QUESTION);
        }
        long total = questionPageInfo.getTotal();

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("成功");
        jsonResult.setData(list);
        jsonResult.put("count", total);
        return jsonResult.getDataMap();
    }

    @PostMapping("/delete")
    @ApiOperation("删除题目的接口")
    @ApiImplicitParam(name = "question", value = "question", paramType = "query", dataTypeClass = Question.class)
    public Map<String, Object> delete(@RequestParam Long id) throws BusinessException {

        // 数据校验
        if (id == null) {
            throw new BusinessException(ExceptionCode.WRONG_REQUIRED);
        }

        Question question = new Question();
        // 设置删除条件
        question.setId(id);

        Integer integer = questionService.deleteById(question);
        if (integer == 0) {
            throw new BusinessException(ExceptionCode.WRONG_DELETE);
        }

        JsonResult jsonResult = new JsonResult();
        jsonResult.setCode("1");
        jsonResult.setMsg("成功");
        return jsonResult.getDataMap();
    }


}
